var util = require('../../../utils/util.js');
var app = getApp();
var today = util.format(new Date(), 'yyyy-MM-dd');
Page({

  data: {
    arrays: [{ name: '男', checked: true, value: '1' }, { name: '女', checked: false, value: '0' }],
    imageList: [],
    imgZ: '',//身份证正面
    imgF: '',//身份证反面
    user_name: '',//用户姓名
    phone_num: '',//电话号码
    certificates_no: '',//证件号码
    room_id: '',//房间号
    jurisdiction_end_time: '',
    orderRoomArray:[],//房间列表
    monthDay: '',
    orderRoomCheck: { value: '', name: '请选择' },
    mouthList: [{ text: '12个月', value: '12', checked: true }, { text: '6个月', value: '6', checked: false }, { text: '3个月', value: '3', checked: false}],
    payMethod: [{ text: '一', value: '1' }, { text: '二', value: '2' }, { text: '三', value: '3' }],
    yaMethod: [{ text: '自定义', value: '-1' },{ text: '一', value: '1' }, { text: '二', value: '2' }, { text: '三', value: '3' }, { text: '四', value: '4' }],
    tableTitle: [{ title: '期数', class: 'one' }, { title: '账期', class: 'two' }, { title: '', class: 'three' }, { title: '账单', class: 'four' }, { title: '最晚支付日', class: 'five' }, { title: '零散与整期合并', class: 'six' }, { title: '是否已支付', class: 'seven' }],
    rent_day:0,//最晚收租日
    beginDate: today,//租约起始日期
    endDate: today,//租约结束日期
    payMethodVlaue: { value: '1', text:'一'},//付款方式的初始值
    yaMethodV: { value: '-1', text: '自定义'},
    init_rent:0,//租金
    network_cost:0,//网费
    init_deposit:0,//押金
    manage_cost:0,//管理费
    custom_cost:0,//自定义周期性费用
    custom_name:'',//自定义周期性费用名称
    initDis:false,//押金是否不可编辑
    tableArray:[],//表单数据
    newtableArray:[],//新的表单数组 合并保存数据使用
    hiddenmodalput:true,
    maxDay:0,
    hiddenmodalput2: true,
    areaCheck: { value: '', name: '请选择' },//小区
    apartmentCheck: { value: '', name: '请选择' },//公寓
    areaArray: [],
    apartmentArray: [],
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    var that = this;
    wx.showLoading({
      title: '加载中...',
    })
    that.onloadData(that);
    //初始化租约结束日期
    var currDate = new Date();
    currDate.setMonth(currDate.getMonth() + 12);
    currDate.setDate(currDate.getDate() - 1);
    //初始化 付款方式值
    let payMethodVlaue = { value: that.data.payMethod[0].value, text: that.data.payMethod[0].text };
    that.setData({
      endDate: util.format(currDate,'yyyy-MM-dd'),
      payMethodVlaue: payMethodVlaue
    })
    //最大的选择时间
    let endseleMaxDate = that.dateAddDays(that.data.beginDate, 30);
    that.setData({
      endseleMaxDate: endseleMaxDate

    })
    //初始化表单数据
    that.billPlan(that);
  },
  /**
   * 页面进入初始化数据
   */
  onloadData:function(that){
    that.getonloadXQ(that);
  },
  /**
    * 文件上传
    */
  chooseImage: function (e) {
    var that = this;
    let hidden = e.currentTarget.dataset.value;

    wx.chooseImage({
      count: 1,
      success: function (res) {
        //缓存下
        wx.showToast({
          title: '正在上传...',
          icon: 'loading',
          mask: true,
          duration: 2000,
          success: function (ress) {

          }
        })
        var tempFilesSize = res.tempFiles[0].size;  //获取图片的大小，单位B
        if (tempFilesSize <= 2000000) {   //图片小于或者等于2M时 可以执行获取图片
          var tempFilePaths = res.tempFilePaths[0]; //获取图片

          wx.uploadFile({
            url: 'https://landlord.kuailezufang.com/app/home/upload',
            filePath: tempFilePaths,
            method: 'post',
            name: 'file',
            formData: {
              'params': 'idcard'
            },
            success: function (res) {
              let data = JSON.parse(res.data);
              if (data.code == 0) {
                wx.showToast({
                  title: '上传成功',  //标题
                  icon: 'none'       //图标 none不使用图标，详情看官方文档
                })
                that.data.imageList.push(tempFilePaths);   //添加到数组
                that.setData({
                  imageList: that.data.imageList
                })
                if (hidden == 'img1') {
                  that.setData({
                    img1: 'none',
                    imgZ: data.data,
                  })
                } else {
                  that.setData({
                    img2: 'none',
                    imgF: data.data
                  })
                }
              } else {
                wx.showToast({
                  title: data.desc,  //标题
                  icon: 'none'       //图标 none不使用图标，详情看官方文档
                })
              }

              //do something  
            }, fail: function (err) {
              wx.showToast({
                title: '上传失败',  //标题
                icon: 'none'       //图标 none不使用图标，详情看官方文档
              })
            }
          });

        } else {    //图片大于2M，弹出一个提示框
          wx.showToast({
            title: '上传图片不能大于2M!',  //标题
            icon: 'none'       //图标 none不使用图标，详情看官方文档
          })
        }

      }
    })
  },
  /**
  * 身份证号码填写
  */
  idcardInput: function (e) {
    this.setData({
      certificates_no: e.detail.value,
    })
  },
  /**
  * 用户填写
  */
  userInput: function (e) {
    this.setData({
      user_name: e.detail.value,
    })
  },
  /**
   * 电话号码填写
   */
  phoneInput: function (e) {
    this.setData({
      phone_num: e.detail.value,
    })
  },
  /**
     * 性别选择
     */
  listenerRadioGroup: function (e) {
    let value = e.detail.value;
   
    let arr = this.data.arrays
    for (let i = 0; i < arr.length; i++) {
      arr[i].checked = false;
      if (arr[i].value ==value) {
        arr[i].checked = true;
      }
    }
    this.setData({
      arrays: arr,
    })
  },
  /**
  * 选择房源
  */
  bindRoomChange: function (e) {
    let name = this.data.orderRoomArray[e.detail.value].house_address;
    let value = e.detail.value;
    let values = this.data.orderRoomArray[e.detail.value].room_id
    let orderRoomCheck = { value: value, name: name };
    let payMethod = this.data.payMethod;
    let yaMethod = this.data.yaMethod;
    let payMethodVlaue={ value: '1', text: '一' };
    let yaMethodV={ value: '-1', text: '自定义' };
    for (let i = 0; i < payMethod.length;i++){
      if (payMethod[i].value ==this.data.orderRoomArray[e.detail.value].rent_num){
          payMethodVlaue = payMethod[i];
          break;
        }
    }
    for (let i = 0; i < yaMethod.length; i++) {
      if (yaMethod[i].value ==this.data.orderRoomArray[e.detail.value].deposit_num) {
        yaMethodV = yaMethod[i];
        break;
      }
    }
    this.setData({
      orderRoomCheck: orderRoomCheck,
      room_id: values,
      network_cost: this.data.orderRoomArray[e.detail.value].network_cost,
      custom_name: this.data.orderRoomArray[e.detail.value].custom_name,
      custom_cost: this.data.orderRoomArray[e.detail.value].custom_cost,
      init_rent: this.data.orderRoomArray[e.detail.value].init_rent,
      manage_cost: this.data.orderRoomArray[e.detail.value].manage_cost,
      rent_day: this.data.orderRoomArray[e.detail.value].rent_day,
      init_deposit: this.data.orderRoomArray[e.detail.value].init_deposit,
      payMethodVlaue: payMethodVlaue,
      yaMethodV: yaMethodV
    })
  },
  /**
   * 电话号码离开文本框事件
   */
  phoneBlur:function(e){
    if(e.detail.value==''){
      return;
    }
    var that=this;
    wx.getStorage({
      key: 'userInfo',
      success: function (res) {
        that.setData({
          userInfo: res.data,

        })
        util.getReq("/app/home/getTenantsDetali", {
          source: res.data.source,
          uid: res.data.user_id,
          phone_num: res.data.phone_num,
          user_name: res.data.user_name,
          "user.phone_num": e.detail.value
        }, function (datas) {
          wx.hideLoading();
          if (datas.code == 0) {
            if (datas.params.user.user_type_id == 10001) {
              let user = datas.params.user;
              let certificates_no = user.certificates_no == null ? '' : user.certificates_no;
              let arr = that.data.arrays
              for (let i = 0; i < arr.length; i++) {
                arr[i].checked = false;
                if (arr[i].value == user.user_sex) {
                  arr[i].checked = true;
                }
              }

              that.setData({
                user_name: user.user_name,
                certificates_no: certificates_no,
                arrays: arr,
              })
              if (user.certificates_img != null && user.certificates_img != '') {
                that.data.imageList.push(user.certificates_img);   //添加到数组
                that.setData({
                  img1: 'none',
                  imgZ: user.certificates_img,
                  imageList: that.data.imageList
                })
              }
              if (user.opposite_img != null && user.opposite_img != '') {
                that.data.imageList.push(user.opposite_img);   //添加到数组
                that.setData({
                  img2: 'none',
                  imgF: user.certificates_img,
                  imageList: that.data.imageList
                })
              }
            } else {
              wx.showToast({
                title: "该手机号已经已非租户身份注册过快乐租房平台，无法使用租客登记。",
                icon: 'none'
              })
            }
          } else {
            var errMsg = '服务器异常';
            if (datas.desc) {
              errMsg = datas.desc;
            }
            wx.showToast({
              title: errMsg,
              icon: 'none'
            })
          }

        })
      }, fail: function () {
        wx.redirectTo({
          url: '/pages/index/index',
        })
      }
    });
  },
  /**
   * 月份点击事件
   */
  mouthbtn:function(e){
    var that=this;
    let value = e.currentTarget.dataset.value;
    let mouthList = that.data.mouthList;
    mouthList = that.mouthreturn(that, value, mouthList);
    that.setData({
      mouthList: mouthList,
    })
    var endDate = new Date(that.data.beginDate);
    endDate.setMonth(endDate.getMonth() + parseInt(value));
    endDate.setDate(endDate.getDate() - 1);
    that.setData({
      endDate: util.format(endDate, 'yyyy-MM-dd'),
    })
    that.billPlan(that);
  },
  /**
   * 返回月份信息
   */
  mouthreturn: function (that, value, mouthList){
    for (let i = 0; i < mouthList.length; i++) {
      mouthList[i].checked = false;
      if (value == mouthList[i].value) {
        mouthList[i].checked = true;
      }
    }
    return mouthList;
  },
  /**
   * 租期始末初始化
   */
  checkDateNum: function (beginDate, endDate,that){
    var endDate3 = new Date(beginDate);
    endDate3.setMonth(endDate3.getMonth() + 3);
    endDate3.setDate(endDate3.getDate() - 1);
    endDate3 = util.format(endDate3, 'yyyy-MM-dd');

    var endDate6 = new Date(beginDate);
    endDate6.setMonth(endDate6.getMonth() + 6);
    endDate6.setDate(endDate6.getDate() - 1);
    endDate6 = util.format(endDate6, 'yyyy-MM-dd');

    var endDate12 = new Date(beginDate);
    endDate12.setMonth(endDate12.getMonth() + 12);
    endDate12.setDate(endDate12.getDate() - 1);
    endDate12 = util.format(endDate12, 'yyyy-MM-dd');

    let mouthList = that.data.mouthList;
    if (endDate == endDate3) {
      mouthList = that.mouthreturn(that, 3, mouthList);
      that.setData({
        mouthList: mouthList,
      })
    } else if (endDate == endDate6) {
      mouthList = that.mouthreturn(that, 6, mouthList);
      that.setData({
        mouthList: mouthList,
      })
    } else if (endDate == endDate12) {
      mouthList = that.mouthreturn(that, 12, mouthList);
      that.setData({
        mouthList: mouthList,
      })
    }
  },

/**
 * 租约开始日期绑定点击事件
 */
  bindBeginDateChange:function(e){
    //去除按钮选择事件
    var that=this;
    let mouthList = that.data.mouthList;
    for (let i = 0; i < mouthList.length; i++) {
      mouthList[i].checked = false;
    }
    that.setData({
      mouthList: mouthList,
    })
    that.setData({
      beginDate:e.detail.value
    })
    that.checkDateNum(that.data.beginDate, that.data.endDate,that);
    that.billPlan(that);
  },
  /**
   * 租约结束日期绑定事件
   */
  bindEndDateChange:function(e){
    var that = this;
    let mouthList = that.data.mouthList;
    for (let i = 0; i < mouthList.length; i++) {
      mouthList[i].checked = false;
    }
    that.setData({
      mouthList: mouthList,
    })
    that.setData({
      beginDate: e.detail.value
    })
    that.checkDateNum(that.data.beginDate, that.data.endDate, that);
    that.billPlan();
  },
  /**
   * 付款方式选择
   */
  bindpayMethod:function(e){
    var that=this;
    let payMethod = that.data.payMethod;
    let text = that.data.payMethod[e.detail.value].text;
    let value = that.data.payMethod[e.detail.value].value;
    let payMethodVlaue = { value: text, text: text };
    that.setData({
      payMethodVlaue: payMethodVlaue, 
    });
    if (that.data.yaMethodV.value!=-1){
      let deposit = that.data.init_rent * (value);
      that.setData({
        init_deposit: deposit,
      });
    }
    that.billPlan(that);
  },
  /**
   * 选择押金方式
   */
  bindyaMethod:function(e){
    var that = this;
    let yaMethod = that.data.payMethod;
    let text = that.data.yaMethod[e.detail.value].text;
    let value = that.data.yaMethod[e.detail.value].value;
    let yaMethodV = { value: value, text: text };
    that.setData({
      yaMethodV: yaMethodV,
    });
    if (value!=-1) {
     
      let deposit = that.data.init_rent * value;
      that.setData({
        init_deposit: deposit,
        initDis: true,
      });
    } else {
      let deposit = that.data.deposit ;
      that.setData({
        initDis: false,
        init_deposit: deposit,
      });
    }
    that.billPlan(that);
  },
  /**
   * 初始化input
   */
  init_rentInput:function(e){
    var that=this;
    if (that.bigDecial(e.detail.value)){
      that.setData({
        init_rent: e.detail.value,
      })
    }else{
      wx.showToast({
        title: '请输入两位小数的金额数据',
        icon:'none',
      })
    }
    
  },
  init_depositInput: function (e) {
    var that = this;
    that.setData({
      init_deposit: e.detail.value,
    })
  },
  manage_costpositInput: function (e) {
    var that = this;
    that.setData({
      manage_costposit: e.detail.value,
    })
  },
  custom_nameInput: function (e) {
    var that = this;
    that.setData({
      custom_name: e.detail.value,
    })
  },
  custom_costInput: function (e) {
    var that = this;
    that.setData({
      custom_cost: e.detail.value,
    })
  },
  rent_dayInput: function (e) {
    var that = this;
    that.setData({
      rent_day: e.detail.value,
    })
  },
  /**
   * 金额校验
   */
  bigDecial:function(mun){
    let reg = new RegExp("^(([1-9]{1}\\d*)|([0]{1}))(\\.(\\d){0,2})?$");
    if (reg.test(mun)){
        return true;
    }
    return false;
  },
  /**
   * 初始化表单数据
   */
  billPlan:function(that){
    let tableArray = [];
    let beginDate = new Date(that.data.beginDate);//租期开始日
    let endDate = new Date(that.data.endDate);//租期截止日
    let beginDateStr = that.data.beginDate; //租期开始日
    let endDateStr = that.data.endDate; //租期截止日
    let days = that.daysBetween(endDateStr, beginDateStr);//租期天数
    let months = that.getIntervalMonth(beginDate, endDate);//租期月数
    let beginDay = beginDate.getDate();             //每期开始日(只包括Day)
    let endDay = beginDay - 1 < 10 ? '0' + (beginDay - 1) : beginDay - 1;//每期截止日(只包括Day)
    let beginMonth = beginDate.getMonth() + 2;        //首期月份
    let beginYear = beginDate.getFullYear();        //首期年份
    let init_rent = that.data.init_rent * 1;    //租金
    let init_deposit = that.data.init_deposit * 1;//押金
    let monthDayCheck = that.data.monthDay * 1;//30：每个月按30天来算；-1：按实际天数来算
    let rent_day = that.data.rent_day;//收租日
    if (rent_day > 31) {
      wx.showToast({
        title: '请输入正确的收租日',
        icon:'none',
      })
      return;
    }
    rent_day = rent_day == '' ? 1 : rent_day;
    rent_day = rent_day < 10 ? '0' + rent_day : rent_day;
    var monthDay;//租金计算天数
    if (days <= 31) {//租期少于一个月
          monthDay = monthDayCheck == -1 ? new Date(new Date(beginDateStr).getFullYear(), new Date(beginDateStr).getMonth() + 1, 0).getDate(): 30;
          let rent1 = init_rent * days / monthDay;
          let be = new Date(beginDateStr);
          be.setMonth(be.getMonth() + 1);
          be.setDate(be.getDate() - 1);
          let bg = util.format(be, 'yyyy-MM-dd');
          if (bg == endDateStr) {
            rent1 = init_rent;
          }
          let tableArray=[];
          tableArray.push({
            id:'1',
            term:1,
            beginDateStr: beginDateStr,
            endDateStr: endDateStr,
            house_rent: '房屋租金￥ ' + (rent1).toFixed(2),
            init_deposit: '房屋押金￥'+init_deposit.toFixed(2),
            checked:false,
            isShow:0,
            rentDate: beginDateStr,//最晚支付日
            length: days / 31 * 100 ,//进度条
          })
    }

    if (beginDay == 1) {//租期开始日为1号
        for (var i = 0; i < months; i++) {
          let maxMonthDay31 = new Date(beginYear, beginMonth - 1, 0);//每月最大天数
          let beginMonth31 = beginMonth - 1 < 10 ? '0' + (beginMonth - 1) : beginMonth - 1;
          let rentDate;//最晚支付日
          let depositStr = i == 0 ? '房屋押金￥' + init_deposit.toFixed(2) + '' : '';//首期押金
          rentDate = beginYear + '-' + beginMonth31 + '-' + rent_day;//最晚支付日
          rentDate = new Date(beginYear, beginMonth31, 0).getDate() < rent_day ? that.curMaxDate(beginYear, beginMonth31 * 1) : rentDate;
          rentDate = new Date(rentDate).getTime() < beginDate.getTime() ? beginDateStr : rentDate;
          let beginDateStr= beginYear + '-' + beginMonth31 + '-01';
          let endDateStr=beginYear + '-' + beginMonth31 + '-' + maxMonthDay31.getDate();
          let term =i+1;
          tableArray.push({
            id: i + 1,
            term: term,
            beginDateStr: beginDateStr,
            endDateStr: endDateStr,
            house_rent: '房屋租金￥ ' + init_rent.toFixed(2),
            init_deposit: depositStr,
            checked: false,//是否选择
            isShow: 0,//是否显示合并
            rentDate: rentDate,//最晚支付日
            length:100 ,//进度条
          })
          if (i + 1 == months) {//最后一期
            if (beginMonth > 12) {
              beginYear++;
              beginMonth = 1;
            }
            beginMonth31 = beginMonth < 10 ? '0' + beginMonth : beginMonth;
            let lastBeginDate31 = beginYear + '-' + beginMonth31 + '-01';//最后一期开始日
            let lastLeaseDay31 = that.daysBetween(endDateStr, lastBeginDate31);//最后一期天数
            rentDate = beginYear + '-' + beginMonth31 + '-' + rent_day;//最晚支付日
            rentDate = new Date(beginYear, beginMonth31, 0).getDate() < rent_day ? that.curMaxDate(beginYear, beginMonth31 * 1) : rentDate;
            rentDate = endDate.getTime() < new Date(rentDate).getTime() ? lastBeginDate31 : rentDate;
            monthDay = monthDayCheck == -1 ? new Date(beginYear, beginMonth31, 0).getDate() : 30;//租金计算天数

            let rent = lastLeaseDay31 / monthDay * init_rent;
            let en = new Date(endDateStr);
            let be = new Date(lastBeginDate31);
            be.setMonth(be.getMonth() + 1);
            be.setDate(be.getDate() - 1);//beginEnd
            let a = util.format(be, 'yyyy-MM-dd');
            let b = util.format(en, 'yyyy-MM-dd')
            if (a == b) {// 如果是一个整月则按整月租金走
              rent = init_rent;
            }
            let che=0;
            if (lastLeaseDay31 < 31 && months > 1){
              che = 1;
            }
            tableArray.push({
              id: i + 2,
              term: i+2,
              beginDateStr: beginYear + '-' + beginMonth31 + '-01',
              endDateStr: endDateStr,
              house_rent: '房屋租金￥ ' + rent.toFixed(2),
              init_deposit: depositStr,
              checked: false,//是否选择
              isShow: che,//是否显示合并
              rentDate: rentDate,//最晚支付日
              length:lastLeaseDay31/monthDay*100
            })
            beginMonth++;
            if (beginMonth > 13 && i + 1 != months) {//月份大于12了并且不是最后一期
              beginYear++;
              beginMonth = 2;
            }
          }

        }

    }else{
      for (let i = 0; i < months; i++) {
        let billWith = 100;//账单进度条宽度
        let che = 0;
        let mergeBtn = i == 0;
        if (mergeBtn&& months == 1){
            che = 1;//是否显示合并
        }
        let endLeaseDay = that.daysBetween(endDateStr, beginDateStr);//最后一期天数
        if (days > 31) {
            if (i + 1 == months && endDay > endDate.getDate()) {//最后一期少于31天(每期截止日大于最后一期的截止日)
                endDay = endDate.getDate() < 10 ? '0' + endDate.getDate() : endDate.getDate();
                billWith = endLeaseDay / 31 * 100;
                init_rent = endLeaseDay / 31 * init_rent;
                if (endLeaseDay < 31 && months > 1){
                    che = 1;//是否显示
                }
            }
              let beginMonthStr = beginMonth < 10 ? '0' + beginMonth : beginMonth;
              let depositStr = i == 0 ? '房屋押金￥' + init_deposit.toFixed(2)  : '';//首期押金
              let curMonth = new Date(beginDateStr).getMonth() + 1;//当前租期月份
              let rentDate = i == 0 ? beginDateStr : (beginYear + '-' + (curMonth < 10 ? '0' + curMonth : curMonth) + '-' + rent_day);//最晚收租日
              rentDate = new Date(beginYear, curMonth, 0).getDate() < rent_day ? that.curMaxDate(beginYear, curMonth) : rentDate;
              let endDateStr = beginYear + '-' + beginMonthStr + '-' + endDay ;
              
              tableArray.push({
                id: i + 1,
                term: i + 1 ,
                beginDateStr: beginDateStr,
                endDateStr: endDateStr,
                house_rent: '房屋租金￥ ' + init_rent.toFixed(2),
                init_deposit: depositStr,
                checked: false,//是否选择
                isShow: che,//是否显示合并
                rentDate: rentDate,//最晚支付日
                length: billWith ,
              })
              beginDateStr = beginYear + '-' + beginMonthStr + '-' + (beginDay < 10 ? '0' + beginDay : beginDay);
              beginMonth++;
              if (beginMonth > 12 && i + 1 != months) {//月份大于12了并且不是最后一期
                beginYear++;
                beginMonth = 1;
              }
            
        }
        if (i + 1 == months && days > 31 && endDay < endDate.getDate()) {//最后一期(每期截止日小于最后一期的截止日)
          monthDay = monthDayCheck == -1 ? new Date(new Date(beginDateStr).getFullYear(), new Date(beginDateStr).getMonth() + 1, 0).getDate() : 30;
          endLeaseDay = that.daysBetween(endDateStr, beginDateStr);
          if (endLeaseDay < 31 && months > 1){
            che = 1;//是否显示合并
          }
          billWith = endLeaseDay < 31 ? endLeaseDay / monthDay * 100 : 100;
          var rentDate = beginYear + '-' + beginMonthStr + '-' + rent_day;
          rentDate = new Date(beginYear, beginMonthStr, 0).getDate() < rent_day ? that.curMaxDate(beginYear, beginMonthStr) : rentDate;
          rentDate = endDate.getTime() < new Date(rentDate).getTime() ? beginDateStr : rentDate;
          tableArray.push({
            id: i + 2,
            term: i + 2 ,
            beginDateStr: beginDateStr,
            endDateStr: endDateStr,
            house_rent: '房屋租金￥ ' + (endLeaseDay / monthDay * init_rent).toFixed(2),
            init_deposit: '',
            checked: false,//是否选择
            isShow: che,//是否显示合并
            rentDate: rentDate,//最晚支付日
            length: billWith ,
          })
        }
      }

    }
    that.setData({
      tableArray: tableArray,
      newtableArray: tableArray
    });
  },
  /**
   * 两个日期之间相差的天数
   */
  daysBetween: function(sDate1, sDate2){
    //Date.parse() 解析一个日期时间字符串，并返回1970/1/1 午夜距离该日期时间的毫秒数
    var time1 = Date.parse(new Date(sDate1));
    var time2 = Date.parse(new Date(sDate2));
    var nDays = Math.abs(parseInt((time2 - time1) / 1000 / 3600 / 24));
    return  nDays + 1;
  },
  /**
   * 两个日期相差的月数
   */
  getIntervalMonth: function(beginDate, endDate){
    var startMonth = beginDate.getMonth();
    var endMonth = endDate.getMonth();
    var intervalMonth = (endDate.getFullYear() * 12 + endMonth) - (beginDate.getFullYear() * 12 + startMonth);
    return intervalMonth;
  },
  /**
   * //获取月份最大日期
   */
  curMaxDate: function(year, month){
    month = month < 10 ? '0' + month : month;
    return year + '-' + month + '-' + new Date(year, month, 0).getDate();
  },
  /**
   * 日期加天数的方法
//dataStr日期字符串
//dayCount 要增加的天数
//return 增加n天后的日期字符串
   */
dateAddDays:function (dataStr, dayCount) {
    var strdate = dataStr; //日期字符串
    var isdate = new Date(strdate.replace(/-/g, "/"));  //把日期字符串转换成日期格式
    isdate = new Date((isdate / 1000 + (86400 * dayCount)) * 1000);  //日期加1天
    var pdate = isdate.getFullYear() + "-" + (isdate.getMonth() + 1) + "-" + (isdate.getDate());   //把日期格式转换成字符串

    return pdate;
  },
  /**
   * //获取某个日期多少天后的日期
   */
  GetDateStr: function(curDate, AddDayCount) {
    var dd = new Date(curDate);
    dd.setDate(dd.getDate() + AddDayCount);//获取AddDayCount天后的日期    
    var y = dd.getFullYear();
    var m = (dd.getMonth() + 1) < 10 ? "0" + (dd.getMonth() + 1) : (dd.getMonth() + 1);//获取当前月份的日期，不足10补0    
    var d = dd.getDate() < 10 ? "0" + dd.getDate() : dd.getDate();//获取当前几号，不足10补0    
    return y + "-" + m + "-" + d;
  },
  /**
   * 单选
   */
  checkOneData:function(e){
    var that = this;
    let checkboxItems;
    var values = e.detail.value;
    checkboxItems = that.data.tableArray;
    for (var i = 0; i < checkboxItems.length; ++i) {
      checkboxItems[i].checked = false;
      for (var j = 0; j < values.length; j++) {
        if (checkboxItems[i].id == values[j]) {
          checkboxItems[i].checked = true;
          break;
        }
      }

    }
    that.setData({
      tableArray: checkboxItems,
    })
  },
  /**
   * 选择租期截止日
   */
  bindendDateChange:function(e){
    var that=this;
    let checkboxItems;
    let beginEnd = e.detail.value;
    let tableArray=[];
    checkboxItems = that.data.tableArray;
    if (checkboxItems.length>0){
      checkboxItems[0].endDateStr = beginEnd;
        that.setData({
          tableArray: checkboxItems,
          newtableArray: tableArray
        })
    }
    let beginDate = new Date(that.data.beginDate);//租期开始日
    let endDate = new Date(that.data.endDate);    //租期截止日
    let beginDateStr = that.data.beginDate;		//租期开始日
    let endDateStr = that.data.endDate;    		//租期截止日
    let beginEndDateStr = beginEnd;			//首期截止日
    let beginEndDate = new Date(beginEnd);	//首期截止日
    let days = that.daysBetween(endDateStr, beginDateStr);//租期天数
    let months = that.getIntervalMonth(beginDate, endDate);//租期月数
    let endDay = beginEndDate.getDate();			//每期截止日(只包括Day)
    let endDayStr1 = endDay + 1 < 10 ? '0' + (endDay + 1) : endDay + 1;
    let beginMonth = beginDate.getMonth() + 2;		//首期月份
    let beginYear = beginDate.getFullYear();		//首期年份
    let beginMonthStr1 = beginMonth < 10 ? '0' + beginMonth : beginMonth;
    let endDayStr2 = endDay < 10 ? '0' + endDay : endDay;
    let beginEndDay = days <= 31 ? days : that.daysBetween(beginEndDateStr, beginDateStr);//首期天数
    let init_rent = that.data.init_rent * 1;    //租金
    let init_deposit = that.data.init_deposit * 1;//押金
    let monthDayCheck = that.data.monthDay * 1;//30：每个月按30天来算；-1：按实际天数来算
    let rent_day = that.data.rent_day;//收租日
    rent_day = rent_day < 10 ? '0' + rent_day : rent_day;
    let monthDay = monthDayCheck == -1 ? new Date(beginYear, beginDate.getMonth() + 1, 0).getDate() : 30;//租金计算天数
    let init_rentONE = (init_rent * beginEndDay / monthDay).toFixed(2)// 第一期租金
    // 戈，补bug
    let be = new Date(that.data.beginDate);
    be.setMonth(be.getMonth() + 1);
    be.setDate(be.getDate() - 1);//beginEnd
    if (util.format(be, 'yyyy-MM-dd') == util.format(beginEndDate, 'yyyy-MM-dd')) {// 如果是一个整月则按整月租金走
      init_rentONE = init_rent;
    }
    let ends = days <= 31 ? endDateStr : beginEndDateStr;
    let che=0;
    if (days > 31 && beginEndDay + 1 < 31){
      che=1;
    }
    tableArray.push({
      id:  1,
      term:  1,
      beginDateStr: beginDateStr,
      endDateStr: ends,
      house_rent: '房屋租金￥ ' + init_rentONE,
      init_deposit: '房屋押金￥ '+init_deposit.toFixed(2),
      checked: false,//是否选择
      isShow: che,//是否显示合并
      rentDate: beginDateStr,//最晚支付日
      length: beginEndDay / monthDay * 100 ,
    })
    let maxDay = new Date(beginEndDate.getYear(), beginEndDate.getMonth() + 1, 0).getDate();//首期月份最大天数
    if (days > 31 && endDay == 30 && endDay != maxDay) {
      for (var i = 0; i < months; i++) {
        var maxMonthDay30 = new Date(beginYear, beginMonth - 2, 0).getDate();//每月最大天数
        var beginMonth30 = beginMonth - 2 < 10 ? '0' + (beginMonth - 2) : beginMonth - 2;//第二期开始月份
        var rentDate;//最晚支付日
        //从第二期开始
        if (i != 0) {
          rentDate = beginYear + '-' + beginMonth30 + '-' + rent_day;
          rentDate = new Date(beginYear, beginMonth30, 0).getDate() < rent_day ? that.curMaxDate(beginYear, beginMonth30 * 1) : rentDate;
          rentDate = new Date(rentDate).getTime() < beginDate.getTime() ? beginDateStr : rentDate;
          tableArray.push({
            id: i + 1,
            term: i + 1 ,
            beginDateStr: beginYear + '-' + beginMonth30 + '-' + maxMonthDay30,
            endDateStr: beginYear + '-' + (beginMonth - 1 < 10 ? '0' + (beginMonth - 1) : beginMonth - 1) + '-' + (new Date(beginYear, beginMonth - 1, 0).getDate() - 1),
            house_rent: '房屋租金￥ ' + init_rent.toFixed(2),
            init_deposit: '',
            checked: false,//是否选择
            isShow: 0,//是否显示合并
            rentDate: rentDate,//最晚支付日
            length: 100 ,
          })
        }
        //最后一期
        if (i + 1 == months) {
          beginMonth30 = beginMonth - 1 < 10 ? '0' + (beginMonth - 1) : beginMonth - 1;
          maxMonthDay30 = new Date(beginYear, beginMonth - 1, 0).getDate();
          let lastBeginDate30 = beginYear + '-' + beginMonth30 + '-' + maxMonthDay30;//最后一期开始日
          let lastLeaseDay30 = that.daysBetween(endDateStr, lastBeginDate30);//最后一期天数
          rentDate = beginYear + '-' + beginMonth30 + '-' + rent_day;
          rentDate = new Date(beginYear, beginMonth30, 0).getDate() < rent_day ? that.curMaxDate(beginYear, beginMonth30) : rentDate;
          rentDate = endDate.getTime() < new Date(rentDate).getTime() ? lastBeginDate30 : rentDate;
          monthDay = monthDayCheck == -1 ? new Date(beginYear, beginMonth30, 0).getDate() : 30;//租金计算天数
          let che=0;
          if (lastLeaseDay31 < 31 && months > 1 ){
            che=1;
          }
          tableArray.push({
            id: i + 2,
            term: i + 2,
            beginDateStr: beginYear + '-' + beginMonth31 + '-01',
            endDateStr: endDateStr,
            house_rent: '房屋租金￥ ' + (lastLeaseDay31 / monthDay * init_rent).toFixed(2),
            init_deposit: '',
            checked: false,//是否选择
            isShow: che,//是否显示合并
            rentDate: rentDate,//最晚支付日
            length: lastLeaseDay31 / monthDay * 100 ,
          })
         
        }
        beginMonth++;
        if (beginMonth > 13 && i + 1 != months) {//月份大于12了并且不是最后一期
          beginYear++;
          beginMonth = 2;
        }
      }
    } else if (days > 31) {
      for (var i = 0; i < months; i++) {
        beginDateStr = i == 1 ? that.GetDateStr(beginEndDateStr, 1) : beginDateStr;//是否是第二期
        beginMonth = beginEndDate.getMonth() == beginDate.getMonth() && i == 1 ? beginMonth - 1 : beginMonth;//是否是第二期，是否跟租期开始日月份相等
        let beginMonthStr2 = beginMonth < 10 ? '0' + beginMonth : beginMonth;//开始月份
        let twoMonthDay = new Date(beginYear, beginMonth, 0).getDate();//二月份天数
        let rentDate;//最晚支付日
        if (i != 0) {
            let endLeaseDate;//月份租期结束日
            rentDate = beginYear + '-' + ((beginMonthStr2 * 1 - 1) < 10 ? '0' + (beginMonthStr2 * 1 - 1) : (beginMonthStr2 * 1 - 1)) + '-' + rent_day;//最晚支付日
            rentDate = new Date(beginYear, beginMonthStr2 * 1 - 1, 0).getDate() < rent_day ? that.curMaxDate(beginYear, beginMonthStr2 * 1 - 1) : rentDate;
            rentDate = new Date(rentDate).getTime() < beginDate.getTime() ? beginDateStr : rentDate;
            if (endDay == 29 && beginMonth == 2) {//租期截止月份为二月份
              endLeaseDate = (beginYear + '-' + beginMonthStr2 + '-' + (twoMonthDay - 1));
              tableArray.push({
                id: i + 1,
                term: i +1 ,
                beginDateStr: beginDateStr,
                endDateStr: endLeaseDate,
                house_rent: '房屋租金￥ ' + init_rent.toFixed(2),
                init_deposit: '',
                checked: false,//是否选择
                isShow: 0,//是否显示合并
                rentDate: rentDate,//最晚支付日
                length:  100 ,
              })
              beginDateStr = beginYear + '-' + beginMonthStr2 + '-' + twoMonthDay;
          } else {
            //最后一期少于31天(每期截止日大于最后一期的截止日)
              endDayStr2 = i + 1 == months && endDay > endDate.getDate() && beginMonth == endDate.getMonth() + 1 ? endDate.getDate() < 10 ? '0' + endDate.getDate() : endDate.getDate() : endDayStr2;
              endLeaseDate = (beginYear + '-' + beginMonthStr2 + '-' + endDayStr2);//月份租期结束日
              tableArray.push({
                id: i + 1,
                term: i + 1 ,
                beginDateStr: beginDateStr,
                endDateStr: endLeaseDate,
                house_rent: '房屋租金￥ ' + init_rent.toFixed(2),
                init_deposit: '',
                checked: false,//是否选择
                isShow: 0,//是否显示合并
                rentDate: rentDate,//最晚支付日
                length: 100 ,
              })
              beginDateStr = beginYear + '-' + beginMonthStr2 + '-' + endDayStr1;
          }
        }
        beginMonth++;
        if (beginMonth > 12 && i + 1 != months) {//月份大于12了并且不是最后一期
          beginYear++;
          beginMonth = 1;
        }
        rentDate = beginYear + '-' + beginMonthStr2 + '-' + rent_day;//最晚支付日
        rentDate = new Date(beginYear, beginMonthStr2, 0).getDate() < rent_day ? that.curMaxDate(beginYear, beginMonthStr2 * 1) : rentDate;
        rentDate = endDate.getTime() < new Date(rentDate).getTime() ? beginDateStr : rentDate;
        monthDay = monthDayCheck == -1 ? new Date(beginYear, beginMonthStr2, 0).getDate() : 30;//租金计算天数
        var endLeaseDay;//最后一期的天数
        if (i + 1 == months && beginMonth == endDate.getMonth() + 1) {//最后一期
          if (that.daysBetween(endDateStr, beginDateStr) > 31) {
            tableArray.push({
              id: i + 2,
              term: i + 2 ,
              beginDateStr: beginDateStr + ' - ' + that.GetDateStr(beginDateStr, 30),
              endDateStr: endDateStr,
              house_rent: '房屋租金￥ ' + init_rent.toFixed(2),
              init_deposit: '',
              checked: false,//是否选择
              isShow: 0,//是否显示合并
              rentDate: rentDate,//最晚支付日
              length: 100 ,
            })
            endLeaseDay = that.daysBetween(endDateStr, that.GetDateStr(that.GetDateStr(beginDateStr, 30), 1));
            let che=0;
            if (endLeaseDay < 31 && months > 1){
              che = 1;
            }
            tableArray.push({
              id: i + 3,
              term: i + 3 ,
              beginDateStr: that.GetDateStr(that.GetDateStr(beginDateStr, 30), 1) ,
              endDateStr: endDateStr,
              house_rent: '房屋租金￥ ' + (endLeaseDay / monthDay * init_rent).toFixed(2),
              init_deposit: '',
              checked: false,//是否选择
              isShow: che,//是否显示合并
              rentDate: rentDate,//最晚支付日
              length: endLeaseDay / monthDay * 100 ,
            })
          }else{
            endLeaseDay = that.daysBetween(endDateStr, beginDateStr);
            let che = 0;
            if (endLeaseDay < 31 && months > 1) {
              che = 1;
            }
            tableArray.push({
              id: i + 2,
              term: i + 2 ,
              beginDateStr: beginDateStr,
              endDateStr: endDateStr,
              house_rent: '房屋租金￥ ' + (endLeaseDay / monthDay * init_rent).toFixed(2),
              init_deposit: '',
              checked: false,//是否选择
              isShow: che,//是否显示合并
              rentDate: rentDate,//最晚支付日
              length: endLeaseDay / monthDay * 100 ,
            })
          }
        }else if (i + 1 == months && beginMonth == endDate.getMonth() + 2) {
          beginDateStr = months > 1 ? beginDateStr : that.GetDateStr(beginEndDateStr, 1);
          endLeaseDay = that.daysBetween(endDateStr, beginDateStr);
          let che = 0;
          if (endLeaseDay < 31 && months > 1) {
            che = 1;
          }
          if (new Date(beginDateStr).getTime() <= endDate.getTime()) {
            tableArray.push({
              id: i + 2,
              term: i + 2,
              beginDateStr: beginDateStr,
              endDateStr: endDateStr,
              house_rent: '房屋租金￥ ' + (endLeaseDay / monthDay * init_rent).toFixed(2),
              init_deposit: '',
              checked: false,//是否选择
              isShow: che,//是否显示合并
              rentDate: rentDate,//最晚支付日
              length: endLeaseDay / monthDay * 100 ,
            })

          }
        }   
      }
    }
    that.setData({
      tableArray: tableArray,
      newtableArray: tableArray
    })
  },
  /**
   * 金额输入完之后
   */
  bigDecialBlur:function(e){
    var that=this;
    that.billPlan(that);
  },
/**
 * 合并
 */
  mergeItem:function(e){
    var that=this;
    let id=e.currentTarget.dataset.id;
    let tableArray = that.data.tableArray;
    if (id != 1 && tableArray.length>0){//不是第一期的情况 最后一期合并
      for (let i = 0; i < tableArray.length;i++){
        if (i == tableArray.length-1){//最后一条
              let obj = tableArray[i]
              let obj2 = tableArray[i-1]//倒数第二条
              tableArray[i - 1].endDateStr = obj.endDateStr;
              tableArray[i - 1].length = obj.length + tableArray[i - 1].length
              tableArray[i - 1].isShow=2;
              tableArray[i - 1].house_rent = tableArray[i].house_rent + tableArray[i-1].house_rent;
              tableArray.splice(i, 1);//删除最后一条
              break;
           }
        }
    } else if (id == 1 && tableArray.length > 0){//第一条数据
      for (let i = 0; i < tableArray.length; i++) {
        if (i ==0) {//第一条数据
          let obj = tableArray[i];
          let obj2 = tableArray[i + 1]//第二期
          tableArray[i].endDateStr = obj2.endDateStr;
          tableArray[i].length = obj2.length + tableArray[i].length
          tableArray.splice(i+1, 1);//删除最后一条
          tableArray[i].isShow = 2;
          tableArray[i].house_rent = tableArray[i].house_rent + tableArray[i + 1].house_rent;
        }else{
          tableArray[i].id=i+1;
          tableArray[i].term = i+1;
        }
      }
    }
    that.setData({
      tableArray: tableArray
    })
  },
 /**
  * 取消合并
  */
  lestItem:function(e){
    var that = this;
    let id = e.currentTarget.dataset.id;
    let tableArray = that.data.tableArray;
    let newtableArray = that.data.newtableArray;
    if (id != 1 && tableArray.length > 0) {//不是第一期的情况 最后一期合并
      for (let i = 0; i < tableArray.length; i++) {
        if (i == tableArray.length - 1) {//最后一条
          let obj = tableArray[i];
          tableArray.splice(i, 1);//删除第一条
          let len = newtableArray.length;
          console.log(len);
          console.log(tableArray);
          tableArray[i] = newtableArray[len - 2];
          tableArray[i+1] = newtableArray[len-1];
          console.log(tableArray);
          break;
        }
      }
    } else if (id == 1 && tableArray.length > 0) {//第一条数据
      for (let i = 0; i < tableArray.length; i++) {
        if (i == 0) {//第一条数据
          let obj = tableArray[i];
          tableArray.splice(i, 1);//删除第一条
          tableArray[i]=newtableArray[i];
          tableArray[i + 1] = newtableArray[i+1];
         
        } else {
          tableArray[i].id = i + 1;
          tableArray[i].term = i + 1;
        }
      }
    }
    that.setData({
      tableArray: tableArray
    })
  },
  /**
   *保存 
   */
  nagtiveToZd:function(e){
    this.setData({
      hiddenmodalput:false,
    })
   
  },
  savesubmit: function (that){
    wx.showLoading({
      title: '保存中请稍后...',
      mask: true,
    })
    let tableArray = that.data.tableArray;
    let subArray = [];
    if (tableArray.length > 0) {
      for (let i = 0; i < tableArray.length; i++) {
        if (i == 0) {
          let house_rent = 0;
          if (tableArray[i].house_rent.split('房屋租金￥')[1]) {
            house_rent = house_rent + parseFloat(tableArray[i].house_rent.split('房屋租金￥')[1]);
          }
          if (tableArray[i].house_rent.split('房屋租金￥')[2]) {
            house_rent = house_rent + parseFloat(tableArray[i].house_rent.split('房屋租金￥')[2]);
          }
          let init_deposit = 0;
          if (tableArray[i].init_deposit.split('房屋押金￥')[1]) {
            init_deposit = init_deposit + parseFloat(tableArray[i].init_deposit.split('房屋押金￥')[1]);
          }
          let totalMon = parseFloat(house_rent) + parseFloat(init_deposit);
          subArray.push({
            lease_term: 1,
            plan_rent_money: totalMon,
            plan_start_date: tableArray[i].beginDateStr,
            plan_end_date: tableArray[i].endDateStr,
            pay_status: tableArray[i].checked == true ? 1 : 0
          })
        } else if (i > 0 && i <= tableArray.length - 2) {
          console.log(tableArray.length - 2);
          let house_rent = 0;
          if (tableArray[i].house_rent.split('房屋租金￥')[i]) {
            house_rent = house_rent + parseFloat(tableArray[i].house_rent.split('房屋租金￥')[i]);
          }
          let totalMon = parseFloat(house_rent) + parseFloat(house_rent);
          subArray.push({
            lease_term: i + 1,
            plan_rent_money: totalMon,
            plan_start_date: tableArray[i].beginDateStr,
            plan_end_date: tableArray[i].endDateStr,
            pay_status: tableArray[i].checked == true ? 1 : 0
          })
        } else if (i == tableArray.length - 1) {
          console.log(i);
          let house_rent = 0;
          if (tableArray[i].house_rent.split('房屋租金￥')[1]) {
            house_rent = house_rent + parseFloat(tableArray[i].house_rent.split('房屋租金￥')[1]);
          }
          if (tableArray[i].house_rent.split('房屋租金￥')[2]) {
            house_rent = house_rent + parseFloat(tableArray[i].house_rent.split('房屋租金￥')[2]);
          }
          subArray.push({
            lease_term: i + 1,
            plan_rent_money: house_rent,
            plan_start_date: tableArray[i].beginDateStr,
            plan_end_date: tableArray[i].endDateStr,
            pay_status: tableArray[i].checked == true ? 1 : 0
          })
        }
      }
    }
    if (that.data.room_id == '' || that.data.phone_num == '' || that.data.user_name == '' ) {
      wx.showToast({
        title: '必填参数不可为空',
        icon: 'none',
      })
      return false;
    }

    if (that.data.custom_cost > 0 && that.data.custom_name == '') {
      wx.showToast({
        title: '请输入自定义周期费用名称',
        icon: 'none',
      })
      return false;
    }

    if (that.data.custom_cost <= 0 && that.data.custom_name != '') {
      wx.showToast({
        title: '请输入自定义周期性费用的金额！',
        icon: 'none',
      })
      return false;
    }
    let reg = new RegExp("/^(\d{4})-(\d{2})-(\d{2})$/");
    if (reg.test(tableArray[0].endDateStr)) {
      wx.showToast({
        title: '第1期的截止日的日期格式不正确！',
        icon: 'none',
      })
      return false;
    }
    if (subArray.length < 1) {
      wx.showToast({
        title: '账单计划有误，请生成账单计划！',
        icon: 'none',
      })
      return false
    }
    let user_sex = '';
    let arrays = that.data.arrays;
    for (let i = 0; i < arrays.length; i++) {
      if (arrays[i].checked == true) {
        user_sex = arrays[i].value;
        break;
      }
    }

    wx.getStorage({
      key: 'userInfo',
      success: function (res) {
        that.setData({
          userInfo: res.data,

        })
        util.getReq("/app/home/addTOrdersFromLandlord", {
          source: res.data.source,
          uid: res.data.user_id,
          phone_num2: res.data.phone_num,
          user_name2: res.data.user_name,
          begin_lease_time: that.data.beginDate,
          plan_end_time: that.data.endDate,
          rent_num: that.data.payMethodVlaue.value,
          deposit_num: that.data.yaMethodV.value,
          init_rent: that.data.init_rent,
          init_deposit: that.data.init_deposit,
          rent_day: that.data.rent_day,
          user_sex: user_sex,
          custom_name: that.data.custom_name,
          custom_cost: that.data.custom_cost,
          manage_cost: that.data.manage_cost,
          network_cost: that.data.network_cost,
          plan_rents: JSON.stringify(subArray),
          zfile: that.data.imgZ,
          ffile: that.data.imgF,
          room_id: that.data.room_id,
          phone_num: that.data.phone_num,
          user_name: that.data.user_name,
          certificates_no: that.data.certificates_no,

        }, function (datas) {
         wx.hideLoading();
          if (datas.code == 0) {
            let maxDay= datas.params.maxDay;
            that.setData({
              maxDay: maxDay,
              hiddenmodalput2:false,
            })
           
          } else {
            wx.showToast({
              title: datas.desc,
              icon: 'none'
            })
          }

        })
      }, fail: function () {
        wx.redirectTo({
          url: '/pages/index/index',
        })
      }
    })
  },
  confirmM:function(){
    var that=this;
    that.setData({
      hiddenmodalput: true,
    })
    that.savesubmit(that);
  
  },
  cancelM:function(){
    this.setData({
      hiddenmodalput: true,
    })
  },
  cancelM2: function () {
    wx.showToast({
      title: '登记成功',
      icon: 'none',
    })
    this.setData({
      hiddenmodalput2: true,
    })
  },
  confirmM2: function () {
    wx.showToast({
      title: '登记成功',
      icon:'none',
    })
    this.setData({
      hiddenmodalput2: true,
    })
  },
  /**
   * 页面初始化查询小区
   */
  getonloadXQ:function(that){
    wx.getStorage({
      key: 'userInfo',
      success: function (res) {
        that.setData({
          userInfo: res.data,

        })
        util.getReq("/app/home/queryOrderArea", {
          source: res.data.source,
          uid: res.data.user_id,
        }, function (datas) {
          wx.hideLoading();
          if (datas.code == 0) {
            let areaArray = datas.data;
            if (datas.data) {
              that.setData({
                areaArray: areaArray,

              })
            }
          } else {
            var errMsg = '服务器异常';
            if (datas.desc) {
              errMsg = datas.desc;
            }
            wx.showToast({
              title: errMsg,
            })
          }

        })
      }
    });
  },
  /**
   * 小区选择
   */
  bindAreaChange: function (e) {
    var that = this;
    let name = that.data.areaArray[e.detail.value].village_name;
    let value = e.detail.value;
    let values = that.data.areaArray[e.detail.value].village_id
    let areaCheck = { value: value, name: name };
    let orderRoomCheck = { value: '', name: '请选择' };
    let apartmentCheck = { value: '', name: '请选择' };
    that.setData({
      areaCheck: areaCheck,
      apartmentCheck: apartmentCheck,
      orderRoomCheck: orderRoomCheck,
      apartmentArray: [],
      orderRoomArray: [],
    })

    wx.getStorage({
      key: 'userInfo',
      success: function (res) {
        util.getReq("/app/home/queryOrderApartment", {
          source: res.data.source,
          uid: res.data.user_id,
          village_id: values
        }, function (datas) {
          wx.hideLoading();
          if (datas.code == 0) {
            if (datas.data) {
              let apartmentArray = datas.data;
              that.setData({
                apartmentArray: apartmentArray,

              })

            } else {
              var errMsg = '服务器异常';
              if (datas.desc) {
                errMsg = datas.desc;
              }
              wx.showToast({
                title: errMsg,
              })
            }
          }
        })
      }
    });
  },
  /**
  * 公寓选择
  */
  bindApartmentChange: function (e) {
    var that = this;
    let name = that.data.apartmentArray[e.detail.value].apartment_name;
    let value = e.detail.value;
    let values = that.data.apartmentArray[e.detail.value].apartment_id;
    let apartmentCheck = { value: value, name: name };
    let orderRoomCheck = { value: '', name: '请选择' };
    that.setData({
      apartmentCheck: apartmentCheck,
      orderRoomCheck: orderRoomCheck,
      orderRoomArray: [],
    })

    wx.getStorage({
      key: 'userInfo',
      success: function (res) {
        that.setData({
          userInfo: res.data,

        })
        util.getReq("/app/home/renterInfo", {
          source: res.data.source,
          uid: res.data.user_id,
          phone_num: res.data.phone_num,
          user_name: res.data.user_name,
          apartment_id: values
        }, function (datas) {
          if (datas.code == 0) {
            let orderRoomArray = [];
            let rooms = datas.params.rooms;
            let monthDay = datas.params.monthDay;
            if (rooms) {
              for (let i = 0; i < rooms.length; i++) {
                orderRoomArray.push({
                  "room_id": rooms[i].room_id,
                  "house_address":  rooms[i].room_code + "室",
                  'network_cost': rooms[i].network_cost,
                  'custom_name': rooms[i].custom_name,
                  'custom_cost': rooms[i].custom_cost,
                  'rent_day': rooms[i].rent_day,
                  'init_rent': rooms[i].month_rent,
                  'init_deposit': rooms[i].month_depost,
                  'manage_cost': rooms[i].manage_cost,
                  'deposit_num': rooms[i].deposit_num,
                  'rent_num': rooms[i].rent_num

                })
              }
            }
            that.setData({
              orderRoomArray: orderRoomArray,
              monthDay: monthDay
            })
            } else {
              var errMsg = '服务器异常';
              if (datas.desc) {
                errMsg = datas.desc;
              }
              wx.showToast({
                title: errMsg,
              })
            }
          
        })
      }
    });
  }
  
})